package com.zhanjixun.weixin.demo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhanjixun.weixin.Weixin;
import com.zhanjixun.weixin.WxMsgHandler;
import com.zhanjixun.weixin.domain.WxMsg;
import com.zhanjixun.weixin.utils.HttpTools;
import com.zhanjixun.weixin.utils.U;
import com.zhanjixun.weixin.utils.UserTools;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.util.stream.Collectors;

/**
 * 图灵机器人
 * http://www.tuling123.com/
 *
 * @author :zhanjixun
 * @date : 2018/11/20 23:04
 */
public class TuLingRoot implements WxMsgHandler {

    private final static String[] QQ_FACE = {
            "[微笑]", "[撇嘴]", "[色]", "[发呆]", "[得意]",
            "[流泪]", "[害羞]", "[闭嘴]", "[睡]", "[大哭]",
            "[尴尬]", "[发怒]", "[调皮]", "[呲牙]", "[惊讶]",
            "[难过]", "[酷]", "[冷汗]", "[抓狂]", "[吐]",
            "[偷笑]", "[愉快]", "[白眼]", "[傲慢]", "[饥饿]",
            "[困]", "[惊恐]", "[流汗]", "[憨笑]", "[悠闲]",
            "[奋斗]", "[咒骂]", "[疑问]", "[嘘]", "[晕]",
            "[疯了]", "[衰]", "[骷髅]", "[敲打]", "[再见]",
            "[擦汗]", "[抠鼻]", "[鼓掌]", "[糗大了]", "[坏笑]",
            "[左哼哼]", "[右哼哼]", "[哈欠]", "[鄙视]", "[委屈]",
            "[快哭了]", "[阴险]", "[亲亲]", "[吓]", "[可怜]",
            "[菜刀]", "[西瓜]", "[啤酒]", "[篮球]", "[乒乓]",
            "[咖啡]", "[饭]", "[猪头]", "[玫瑰]", "[凋谢]",
            "[嘴唇]", "[爱心]", "[心碎]", "[蛋糕]", "[闪电]",
            "[炸弹]", "[刀]", "[足球]", "[瓢虫]", "[便便]",
            "[月亮]", "[太阳]", "[礼物]", "[拥抱]", "[强]",
            "[弱]", "[握手]", "[胜利]", "[抱拳]", "[勾引]",
            "[拳头]", "[差劲]", "[爱你]", "[NO]", "[OK]",
            "[爱情]", "[飞吻]", "[跳跳]", "[发抖]", "[怄火]",
            "[转圈]", "[磕头]", "[回头]", "[跳绳]", "[投降]",
            "[激动]", "[乱舞]", "[献吻]", "[左太极]", "[右太极]"};

    public static void main(String[] args) {
        Weixin weixin = Weixin.getInstance();
        weixin.login();
        String nickName = weixin.getWxInitDataDTO().getUser().getNickName();
        Weixin.getInstance().getMessenger().sendTextMsg(UserTools.remarkName2userName("大号"), String.format("🤖机器人[%s]已启动.", nickName));
        weixin.setMsgHandler(new TuLingRoot());
    }

    @Override
    public void handleTextMsg(WxMsg msg) {
        if (StringUtils.startsWithAny(msg.getContent(), "求图", "斗图")) {
            String content = msg.getContent().replace("求图", "").replace("斗图", "");
            if (StringUtils.isBlank(content)) {
                for (String img : DouTuLa.hotList().stream().distinct().limit(5).collect(Collectors.toSet())) {
                    String imgFilePath = DouTuLa.downloadImage(img);
                    if (imgFilePath != null) {
                        Weixin.getInstance().getMessenger().sendEmoticonMsg(msg.getFromUserName(), new File(imgFilePath));
                    }
                    U.sleep(200);
                }
            } else {
                String imgFilePath = DouTuLa.downloadImage(DouTuLa.searchPic(content).get(0));
                if (imgFilePath != null) {
                    Weixin.getInstance().getMessenger().sendEmoticonMsg(msg.getFromUserName(), new File(imgFilePath));
                }
            }
        } else {
            String userId = msg.getFromUserName().length() > 10 ? msg.getFromUserName().substring(msg.getFromUserName().length() - 10) : msg.getFromUserName();
            String message = postText(msg.getContent(), userId);
            if (StringUtils.isNotBlank(message)) {
                Weixin.getInstance().getMessenger().sendTextMsg(msg.getFromUserName(), message);
            } else {
                String imgFilePath = DouTuLa.downloadImage(DouTuLa.searchPic(msg.getContent()).get(0));
                if (imgFilePath != null) {
                    Weixin.getInstance().getMessenger().sendEmoticonMsg(msg.getFromUserName(), new File(imgFilePath));
                }
            }
        }
    }

    @Override
    public void handleImageMsg(WxMsg msg) {
        File file = Weixin.getInstance().getDownloader().downloadImage(msg.getMsgId());
        try {
            File output = new File("download", StringUtils.substringBefore(file.getName(), ".") + ".gif");
            ImageIO.write(ImageIO.read(file), "gif", output);
            Weixin.getInstance().getMessenger().sendEmoticonMsg(msg.getFromUserName(), output);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void handleRevokeMsg(WxMsg msg) {

    }

    @Override
    public void handleEmoticonMsg(WxMsg msg) {

    }

    @Override
    public void handleVoiceMsg(WxMsg msg) {

    }

    @Override
    public void handleVideoMsg(WxMsg msg) {

    }

    @Override
    public void handleFileMsg(WxMsg msg) {

    }

    @Override
    public void handleLinkMsg(WxMsg msg) {

    }

    @Override
    public void handleLocationMsg(WxMsg msg) {

    }

    @Override
    public void handleSysMsg(WxMsg msg) {

    }

    @Override
    public void handleCardMsg(WxMsg msg) {

    }

    @Override
    public void handleMiniProgramMsg(WxMsg msg) {

    }

    private static String postText(String text, String userId) {
        JSONObject userInfo = new JSONObject();
        userInfo.put("apiKey", "2f7fcaa393b649feabb9a5ffc6af7a7e");
        userInfo.put("userId", userId);

        JSONObject inputText = new JSONObject();
        inputText.put("text", text);

        JSONObject perception = new JSONObject();
        perception.put("inputText", inputText);

        JSONObject root = new JSONObject();
        root.put("reqType", 0);//输入类型:0-文本(默认)、1-图片、2-音频
        root.put("userInfo", userInfo);
        root.put("perception", perception);

        try {
            HttpResponse httpResponse = HttpTools.post("http://openapi.tuling123.com/openapi/api/v2", root.toJSONString());
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return JSON.parseObject(HttpTools.toUTF8String(httpResponse))
                        .getJSONArray("results")
                        .getJSONObject(0)
                        .getJSONObject("values")
                        .getString("text");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

}
